package com.example.operation.service.impl;


import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.operation.domin.DecWaresImg;
import com.example.operation.mapper.DecWaresImgMapper;
import com.example.operation.service.DecWaresImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @ClassName: DecWaresImgServiceImpl
 * @Description:
 * @Author
 * @Date 2021/11/28
 * @Version 1.0
 */

@Service
public class DecWaresImgServiceImpl extends ServiceImpl<DecWaresImgMapper, DecWaresImg> implements DecWaresImgService {


    @Autowired
    private DecWaresImgMapper decWaresImgMapper;


    /**
     * 添加图片
     * @param img 图片
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public DecWaresImg addpicture(MultipartFile img) {
        DecWaresImg decWaresImg = new DecWaresImg();
        //获取文件名
        String originalFilename = img.getOriginalFilename();
        //文件重命名
        String newName = UUID.randomUUID() + "_" + originalFilename;
        //上传文件的存储路径
        String filePath = "D:\\Photoshop CC2020\\记录\\";
        //判断路径是否存在
        Boolean aBoolean = FileUtil.exist(filePath);
        if (!aBoolean) {
            //新建存储路径
            FileUtil.mkdir(filePath);
        }
        File file1 = FileUtil.file(filePath + newName);
        try {
            //将文件存储到该位置
            img.transferTo(file1);
            //将文件名存储到数据库
            decWaresImg.setImg(filePath + newName);

            decWaresImgMapper.insert(decWaresImg);
        }
        catch (
                FileNotFoundException e) {
            e.printStackTrace();

        } catch (
                IOException e) {
            e.printStackTrace();
        }
        DecWaresImg decWaresImg1 = this.getOne(new LambdaQueryWrapper<DecWaresImg>().eq(DecWaresImg::getImg,decWaresImg.getImg()));
        return decWaresImg1;
    }


    /**
     * 删除图片
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Integer id) {
        //删除磁盘图片
       DecWaresImg decWaresImg = this.getById(id);
       if(decWaresImg == null){
           throw new RuntimeException("");
       }
       File file = FileUtil.file(decWaresImg.getImg());
       FileUtil.del(file);
       this.removeById(id);

    }

}
